#pragma once
#include <cstdlib>
#include <iostream>
#include <cstring>
#include <string>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/stat.h>
#include <unistd.h>

const int back_log = 10;

enum
{
    Socket_Error = 1,
    Bind_Error,
    Listen_Error,
};
class Socket
{
public:
    Socket(){};
    ~Socket(){};
    void Build_Socket()
    {
        socket_fd = socket(AF_INET, SOCK_STREAM, 0);
        if (socket_fd < 0)
        {
            std::cerr << "socket创建失败" << std::endl;
            exit(Socket_Error);
        }
    }
    void Bind(uint16_t port)
    {
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_port = htons(port);
        local.sin_family = AF_INET;
        local.sin_addr.s_addr = INADDR_ANY;
        socklen_t len = sizeof(local);
        if (bind(socket_fd, (struct sockaddr *)&local, len) < 0)
        {
            std::cerr << "Bind 失败" << std::endl;
            exit(Bind_Error);
        }
    }
    void Listen()
    {
        if (listen(socket_fd, back_log) < 0)
        {
            std::cerr << "Listen 失败" << std::endl;
            exit(Listen_Error);
        }
    }
    bool Connect(const std::string &ip, const uint16_t &port)
    {
        struct sockaddr_in peer;
        memset(&peer, 0, sizeof(peer));
        peer.sin_family = AF_INET;
        peer.sin_port = htons(port);
        inet_pton(AF_INET, ip.c_str(), &peer.sin_addr);
        int len = sizeof(peer);
        int n = connect(socket_fd, (struct sockaddr *)&peer, len);
        if (n < 0)
        {
            std::cerr << "Connect Error"
                      << "port , ip " << port << " " << ip << std::endl;
            return false;
        }
        return true;
    }
    int Accept(std::string *ip, uint16_t *port)
    {
        struct sockaddr_in peer;
        memset(&peer, 0, sizeof(peer));
        socklen_t len = sizeof(peer);
        int new_fd = accept(socket_fd, (struct sockaddr *)&peer, &len);
        if (new_fd < 0)
        {
            std::cerr << "Accept 失败" << std::endl;
            return -1;
        }
        *port = ntohs(peer.sin_port);
        char ipstr[64];
        inet_ntop(AF_INET, &peer.sin_addr, ipstr, sizeof(ipstr));
        *ip = ipstr;
        return new_fd;
    }

    int Fd()
    {
        return socket_fd;
    }
    void Close()
    {
        close(socket_fd);
    }

private:
    int socket_fd;
};